/// <reference path="../Scripts/jquery-1.7.1.min.js" />
/// <reference path="../Scripts/knockout-2.1.0.js" />

function UsersInRolesViewModel() {
    var self = this;
    // put a property loop here
    self.UsersInRoleID = ko.observable();
    self.TS = ko.observable();
    self.CreatedBy = ko.observable();
    self.CreatedDt = ko.observable();
    self.ModifiedBy = ko.observable();
    self.ModifiedDt = ko.observable();
    self.UserId = ko.observable();
    self.ApplicationRoleId = ko.observable();
    self.Action = ko.observable();
    self.Caller = ko.observable();
    self.Role = ko.observable();
    self.PageSize = ko.observable();
    self.PageNumber = ko.observable();
    self.SortColumn = ko.observable();
    self.SortType = ko.observable();
    self.TotalRows = ko.observable();
    self.ApplicationRoles = ko.observable();
    self.UserProfile = ko.observable();

    self.UserProfileList = ko.observableArray([]);
    self.ApplicationRolesList = ko.observableArray([]);


    self.selectedChoice = ko.observableArray([]);
    //self.selectedUser = ko.observableArray([]);
    self.selected = ko.observableArray();

    self.selectedVal = ko.observableArray([]);
    self.selectedVal2 = ko.observableArray([]);
    self.EditingRoles = ko.observable();
    self.selectedItem = ko.observable();
    self.eroleid = ko.observableArray();
    self.LoadingUserinroles = ko.observable();
    self.selectedUser = ko.observable();
    self.euserid = ko.observableArray();

    self.dropdownText = ko.observableArray();
    
    


    self.multipleSelectedOptionValues = ko.observableArray([]),


    self.UsersInRolesList = ko.observableArray([]);
    self.setUsersInRoles = function (
			UsersInRoleID, TS, CreatedBy, CreatedDt, ModifiedBy, ModifiedDt, UserId, ApplicationRoleId, _Action, _Caller, _Role, _PageNumber, _PageSize, _SortColumn, _SortType, _TotalRows

	) {

        UsersInRoleID = _UsersInRoleID;
        TS = _TS;
        CreatedBy = _CreatedBy;
        CreatedDt = _CreatedDt;
        ModifiedBy = _ModifiedBy;
        ModifiedDt = _ModifiedDt;
        UserId = _UserId;
        ApplicationRoleId = _ApplicationRoleId;
        Action = _Action;
        Caller = _Caller;
        Role = _Role;
        PageSize = _PageSize
        PageNumber = _PageNumber;
        SortColumn = _SortColumn;
        SortType = _SortType;
        TotalRows = _TotalRows;

    }; //  End of set procedure 


    //select available  users 
    self.availableUser = function () {
        var self = this;
        this.Action = "GetAll";
        this.Caller = "trooks";
        this.Role = "user";

        jQuery.ajax({
            url: "./api/UserProfileapi/",
            type: 'get',
            data: { Action: self.Action, Caller: self.Caller, Role: self.Role, PageNumber: self.PageNumber, PageSize: self.PageSize, SortColumn: self.SortColumn, SortType: self.SortType },
        }).done(function (data) {
            //self.UserProfileList.removeAll();
            self.euserid.removeAll();
            self.auserid.removeAll();
            $.each(data, function (key, val) {
                self.euserid.push(new userItem(val.UserId, val.UserName));
                self.auserid.push(new userItem(val.UserId, val.UserName));
            })
        });
    };

    //select available  Roles    
    self.availableRoles = function () {
        var self = this;
        self.Action = "GetAll";
        self.Caller = "trooks";
        self.Role = "user";
        self.PageNumber = "1";
        self.PageSize = "10";
        self.SortColumn = "ApplicationRoleId";
        self.SortType = "Asc";

        jQuery.ajax({
            url: "./api/ApplicationRolesApi/",
            type: 'get',
            data: { Action: self.Action, Caller: self.Caller, Role: self.Role, PageNumber: self.PageNumber, PageSize: self.PageSize, SortColumn: self.SortColumn, SortType: self.SortType },
        }).done(function (data) {
            self.eroleid.removeAll();
            self.aroleid.removeAll();

            $.each(data, function (key, val) {

                self.eroleid.push(new roleItem(val.ApplicationRoleId, val.RoleName, val.Application.ApplicationName));
                self.aroleid.push(new roleItem(val.ApplicationRoleId, val.RoleName,val.Application.ApplicationName));

            })
        });
    };


    //Add User validation
    self.AddUsersInRoles = function () {
        self.Action = "Add";
        self.Caller = "trooks";
        //validation 
        $("#form-add").validate({
        });
        if (!$("#form-add").valid()) {
            //alert("Invalied");
            return;
        }
        
        var arr = self.multipleSelectedOptionValues();       
        jQuery.each(arr, function (i, val) {
            jQuery.ajax({
                url: "./api/UsersInRolesapi/",
                type: 'post',
               // data: { Action: self.Action, Caller: self.Caller, Role: self.Role, CreatedBy: self.CreatedBy, CreatedDt: self.CreatedDt, ModifiedBy: self.ModifiedBy, ModifiedDt: self.ModifiedDt,  },
                data: ko.toJSON({ Action: self.Action, Caller: self.Caller, UserId: self.selectedVal().UserId, ApplicationRoleId: val.ApplicationRoleId }),
                contentType: 'application/json; charset=utf-8',
                success: function (result) {

                    $('#myModaladd').modal('hide');
                    self.GetUsersInRolesByParameter();
                    //alert(result);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                $('#error-dis').text(thrownError);
                $('#register-error').css({ 'display': 'block' });
                $('#SearchFilter-home').css({ 'display': 'none' });
                $('#myModaladd').modal('hide');
                $(document).scrollTop(0);
            }

            });
        });
    };
  
    self.LoadUserinroles = function (appVal2) {
        self.LoadingUserinroles(appVal2);

        //self = appVal2;
    };

    //Delete User Roles
    self.DeleteUserinroles = function (appval) {
        self.Action = "Remove";
        self.Caller = "trooks";
        self.Role = "user";
        jQuery.ajax({
            url: "./api/UsersInRolesapi/",
            type: 'post',
            // data: { Action: self.Action, Caller: self.Caller, Role: self.Role, CreatedBy: self.CreatedBy, CreatedDt: self.CreatedDt, ModifiedBy: self.ModifiedBy, ModifiedDt: self.ModifiedDt,  },
            data: ko.toJSON({ Action: self.Action, Caller: self.Caller, UserId: appval.UserId, UsersInRoleID: appval.UsersInRoleID, TS: appval.TS }),
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                $('#Modaldel').modal('hide');                               
                self.GetUsersInRolesByParameter();
            },
            error: function (xhr, ajaxOptions, thrownError) {
            $('#error-dis').text(thrownError);
            $('#register-error').css({ 'display': 'block' });
            $('#SearchFilter-home').css({ 'display': 'none' });
            $('#Modaldel').modal('hide');
            $(document).scrollTop(0);
        }

        });
        
    };


    //Edit User Roles

    function roleItem(id, name, appName) {
        this.ApplicationRoleId = ko.observable(id);
        this.RoleName = ko.observable(name);
        this.ApplicationName = ko.observable(appName);
        this.computedData = ko.computed(function () {
            return this.RoleName() + ' (' + this.ApplicationName()+')';
        },this);
    }

    function userItem(uid, uname) {
        this.UserId = ko.observable(uid);
        this.UserName = ko.observable(uname);

    }

    self.EditRoles = function (appVal) {
        self.euserid = ko.observableArray([new userItem(appVal.UserId, "")]);
        self.eroleid = ko.observableArray([new roleItem(appVal.ApplicationRoleId, "")]);
        self.availableUser(appVal);

        self.EditingRoles(appVal);
        self.availableRoles(appVal);
    };


    //adding User Roles

    self.aroleid = ko.observableArray();
    self.auserid = ko.observableArray();

    self.AddingRoles = ko.observable();
    self.AddRoles = function (appVal2) {
        self.availableUser(appVal2);
        self.availableRoles(appVal2);
        self.AddingRoles(appVal2);

    };

    // compleate edit and update data     
    self.UpdateUserinroles = function (appval) {
        self.Action = "Update";
        self.Caller = "trooks";
        self.Role = "user";
        CreatedBy = ""
        self.CreatedBy = "fafafafa";

        jQuery.ajax({
            url: "./api/UsersInRolesapi/",
            //data: { Action: self.Action, Caller: self.Caller, Role: self.Role, CreatedBy: self.CreatedBy, CreatedDt: self.CreatedDt, ModifiedBy: self.ModifiedBy, ModifiedDt: self.ModifiedDt, UserId: self.selectedUser, ApplicationRoleId: self.selectedItem },
            data: ko.toJSON({ Action: self.Action, Caller: self.Caller, Role: self.Role, UserId: appval.UserId, ApplicationRoleId: self.selectedItem, UsersInRoleID: appval.UsersInRoleID, TS: appval.TS, CreatedBy: appval.CreatedBy, CreatedDt: appval.CreatedDt, ModifiedBy: appval.ModifiedBy, ModifiedDt: appval.ModifiedDt }),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (result) {

                $('#Modaledit').modal('hide');
                self.GetUsersInRolesByParameter();
                //alert(result);
            },
            error: function (xhr, ajaxOptions, thrownError) {
            $('#error-dis').text(thrownError);
            $('#register-error').css({ 'display': 'block' });
            $('#SearchFilter-home').css({ 'display': 'none' });
            $('#Modaledit').modal('hide');
            $(document).scrollTop(0);
        }
        });

    }; //End of add procedure

    // loading model popup
    ko.bindingHandlers['modal'] = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var allBindings = allBindingsAccessor();
            var $element = $(element);
            $element.addClass('hide modal');

            if (allBindings.modalOptions) {
                if (allBindings.modalOptions.beforeClose) {
                    $element.on('hide', function () {
                        return allBindings.modalOptions.beforeClose();
                    });
                }
            }

            return ko.bindingHandlers['with'].init.apply(this, arguments);
        },
        update: function (element, valueAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor());

            var returnValue = ko.bindingHandlers['with'].update.apply(this, arguments);

            if (value) {
                $(element).modal('show');
            } else {
                $(element).modal('hide');
            }

            return returnValue;
        }
    };

    //filter and loading data

    self.UsersInRolesList = ko.observableArray([]);
    self.filter = ko.observable("");

    self.filteredRoles = ko.computed(function () {
        var filterText = self.filter().toLowerCase();
        return ko.utils.arrayFilter(self.UsersInRolesList(), function (item) {
            return filterText.length < 1 || item.ApplicationRoles.RoleName == filterText || item.UserProfile.UserName.toLowerCase().indexOf(filterText) != -1
        });

    }, self);

    //self.data = ko.observableArray([
    //   new roleItem(1, "One description"),
    //   new roleItem(2, "Two description"),
    //   new roleItem(3, "Three description")]);
    //self.computedData = ko.computed(function () {
    //    //return ko.utils.arrayMap(self.data(), function (roleItem) {
    //        return  roleItem.RoleName + ' ' + roleItem.ApplicationName ;
    //    //});
    //});
    //loading data to table
    self.GetUsersInRolesByParameter = function () {
        
        

        this.Action = "GetAll";
        this.Caller = "trooks";
        this.Role = "user";
        this.PageNumber = 1;
        this.PageSize = 10;
        this.SortColumn = "UsersInRoleID";
        this.SortType = "asc";        
        jQuery.ajax({
            url: "./api/UsersInRolesapi/",
            data: { Action: self.Action, Caller: self.Caller, Role: self.Role, PageNumber: self.PageNumber, PageSize: self.PageSize, SortColumn: self.SortColumn, SortType: self.SortType },
            type: 'get',

            success: function (result) {
                self.UsersInRolesList.removeAll();
                $.each(result, function (key, val) {
                    self.UsersInRolesList.push(
                        val
                    )
                })
            },
            error: function (xhr, ajaxOptions, thrownError) {
                $('#error-dis').text(thrownError);
                $('#register-error').css({ 'display': 'block' });
                $('#SearchFilter-home').css({ 'display': 'none' });                
                $(document).scrollTop(0);
            }
       
        });
        if (loginUserRole.indexOf('user') > -1) {
            $('.add-btn').attr('disabled', 'disabled');
        }
    };


    //Sort list
    self.sortRecords = ko.observableArray();

    ko.bindingHandlers.sort = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var asc = false;
            element.style.cursor = 'pointer';

            element.onclick = function () {
                var value = valueAccessor();
                var prop = value.prop;
                var data = value.arr;

                asc = !asc;
                if (asc) {
                    self.UsersInRolesList.sort(function (left, right) {
                        return left[prop] == right[prop] ? 0 : left[prop] < right[prop] ? -1 : 1;
                    });
                } else {
                    self.UsersInRolesList.sort(function (left, right) {
                        return left[prop] == right[prop] ? 0 : left[prop] > right[prop] ? -1 : 1;
                    });
                }
            }
        }
    };


}; //End of view model







